
const express=require('express');
const router=express.Router();


const Variety=require("../../models/Variety");

router.post("/add",(req,res)=>{
    const name=req.query.name;
    const number=req.query.number.map(v=>JSON.parse(v));
    Variety.findOne({'name': name})
    .then(workshop=>{
        if(workshop){
            return res.json({
                code:400,
                message:'该名称已被使用'
            })
        }
         new Variety({
            name, number
        }).save()
        .then(workshop=>res.json({
            code:200,
            data:workshop
        }))
        .catch(err=>console.log(err))
    })
})

router.post("/getList",(req,res)=>{
    const limit=req.query.limit;
    const page=req.query.page;
    Variety.find({})
    .then(workshops=>{
        const pageList = workshops.filter((item, index) => index < limit * page && index >= limit * (page - 1))
        res.json({
            code:200,
            list:pageList,
            total:workshops.length
        });
    })
})

router.post("/update",(req,res)=>{
    const name=req.body.name;
    Variety.updateOne({name: name}, {name, number: req.body.number})
    .then(()=>{
        res.json({
            code:200,
            message:'更新成功'
        });
    })
})

router.post("/delete",(req,res)=>{
    const name=req.query.name;
    Variety.deleteOne({name: name})
    .then(()=>{
        res.json({
            code:200,
            message:'删除成功'
        });
    })
})

module.exports=router;